#!/usr/bin/env python
# encoding: utf-8

import time
import json
import logging
import threading
import hashlib
import os
import random
from datetime import datetime

from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.triggers.cron import CronTrigger
from django.db import connections
from django.forms.models import model_to_dict
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.executors.pool import ThreadPoolExecutor
from fly2018.db_conf import magic_redis, redis_host, redis_port, redis_pwd, redis_db_name
from apps.magic_models import MagicMockProfit
from fly2018 import db_conf
from fly2018.logging_conf import log_common

logger = logging.getLogger(__name__)

db_time_format = "%Y-%m-%d %H:%M:%S"

executors = {
    'default': ThreadPoolExecutor(5)
}

redis_args = {
    'host': redis_host,
    'port': redis_port,
    'db': redis_db_name,
    'password': redis_pwd
}

# redis_job_store =
# RedisJobStore(jobs_key='_apscheduler.jobs', run_times_key='sync_apscheduler.run_times', **redis_args)
memory_job_store = MemoryJobStore()
scheduler = BackgroundScheduler(executors=executors)
scheduler.add_jobstore(memory_job_store, "default")

"""
产生广告收益模拟数据
日期、自动生成， 格式为：2019-02-14
广告位、固定名称：咪咕阅读APP焦点图
广告位ID、固定名称：ID:256472
展示数、公式生成：计算公式：当日收益除以2
点击数、公式生成：计算公式：展示数*点击率（点击率随机在千分之7-9之间生成。）
eCPM（元）、固定：2.00元
当日收益（元）、动态生成：在800.00-1300.00元之间，随机取数，精确到小数点两位。
"""


def md5(md5_char):
    """
    md5算法
    :param md5_char:
    :return:
    """
    hash_md5 = hashlib.md5(md5_char.encode("utf-8"))
    return hash_md5.hexdigest()


class CreateSchedulerWork(threading.Thread):
    def __init__(self, scheduler):
        super(CreateSchedulerWork, self).__init__()
        self.scheduler = scheduler
        self.setDaemon(True)

    def run(self):

        # 50 6 * * *
        scheduler.add_job(self.fake_adv1, CronTrigger.from_crontab('01 14 * * *'))
        # 'interval',days  = 03,hours = 17,minutes = 19,seconds = 07
        scheduler.add_job(self.fake_adv2, CronTrigger.from_crontab('12 14 * * *'))
        # scheduler.add_job(self.fake_adv2, 'interval', days=1, hours=22, minutes=53)

    def fake_adv1(self):
        adv1_id = "256472"
        adv1_name = ""
        dt = datetime.now()
        dt_format = dt.strftime('%Y-%m-%d')
        mp_results = MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=adv1_id)
        per_profit = round(random.uniform(700, 1000), 2)
        adv_views = int(per_profit * 500)
        adv_clicks = int((adv_views * random.uniform(7, 10)) / 10)
        if not mp_results:
            MagicMockProfit.objects.create(adv_id=adv1_id, adv_views=adv_views,
                                           adv_clicks=adv_clicks, adv_eCPM=2, adv_profit=per_profit,
                                           adv_date=dt_format, is_deleted=0)
        else:
            MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=adv1_id).update(
                adv_views=adv_views, adv_clicks=adv_clicks, adv_profit=per_profit)

    def fake_adv2(self):
        adv2_id = "264659"
        adv2_name = ""
        dt = datetime.now()
        dt_format = dt.strftime('%Y-%m-%d')
        mp_results = MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=adv2_id)
        per_profit = round(random.uniform(20, 50), 2)
        adv_views = int(per_profit * 500)
        adv_clicks = int((adv_views * random.uniform(7, 10)) / 10)
        if not mp_results:
            MagicMockProfit.objects.create(adv_id=adv2_id, adv_views=adv_views,
                                           adv_clicks=adv_clicks, adv_eCPM=2, adv_profit=per_profit,
                                           adv_date=dt_format, is_deleted=0)
        else:
            MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=adv2_id).update(
                adv_views=adv_views, adv_clicks=adv_clicks, adv_profit=per_profit)


register_events(scheduler)
scheduler.start()
log_common.warn("产生广告收益模拟数据开始")
add_work = CreateSchedulerWork(scheduler)
add_work.start()
